<template>
  <div class="character-sheet">
    <div class="sheet-header">
      <h3>
        <el-icon><User /></el-icon>
        角色卡
      </h3>
      <div class="header-actions">
        <el-button size="small" @click="exportCharacter">导出</el-button>
        <el-button size="small" @click="importCharacter">导入</el-button>
        <el-button size="small" @click="saveCharacter" :loading="saving">保存</el-button>
      </div>
    </div>

    <div class="sheet-content">
      <!-- 基础信息 -->
      <el-card class="info-card" shadow="never">
        <template #header>
          <div class="card-header">
            <el-icon><Edit /></el-icon>
            <span>基础信息</span>
          </div>
        </template>
        
        <el-form :model="character" label-width="80px" size="small">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="角色名">
                <el-input v-model="character.name" placeholder="请输入角色名" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="职业">
                <el-input v-model="character.profession" placeholder="请输入职业" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-card>

      <!-- 基础属性 -->
      <el-card class="stats-card" shadow="never">
        <template #header>
          <div class="card-header">
            <el-icon><TrendCharts /></el-icon>
            <span>基础属性</span>
          </div>
        </template>
        
        <div class="stats-grid">
          <div 
            v-for="(value, stat) in character.stats" 
            :key="stat"
            class="stat-item"
          >
            <div class="stat-label">{{ getStatLabel(stat) }}</div>
            <div class="stat-value">
              <el-input-number
                v-model="character.stats[stat]"
                :min="0"
                :max="100"
                size="small"
                controls-position="right"
              />
            </div>
            <div class="stat-modifier">
              {{ getStatModifier(value) }}
            </div>
          </div>
        </div>
      </el-card>

      <!-- 生命值/魔法值 -->
      <el-card class="hp-mp-card" shadow="never">
        <template #header>
          <div class="card-header">
            <el-icon><Warning /></el-icon>
            <span>生命值/魔法值</span>
          </div>
        </template>
        
        <div class="hp-mp-grid">
          <div class="hp-item">
            <div class="label">生命值 (HP)</div>
            <div class="value-container">
              <el-input-number
                v-model="character.hp"
                :min="0"
                :max="999"
                size="small"
                controls-position="right"
              />
              <span class="max-value">/ {{ calculateHP() }}</span>
            </div>
            <el-progress 
              :percentage="(character.hp / calculateHP()) * 100" 
              :color="getHPColor()"
              :show-text="false"
            />
          </div>
          
          <div class="mp-item">
            <div class="label">魔法值 (MP)</div>
            <div class="value-container">
              <el-input-number
                v-model="character.mp"
                :min="0"
                :max="999"
                size="small"
                controls-position="right"
              />
              <span class="max-value">/ {{ calculateMP() }}</span>
            </div>
            <el-progress 
              :percentage="(character.mp / calculateMP()) * 100" 
              color="#409eff"
              :show-text="false"
            />
          </div>
          
          <div class="san-item">
            <div class="label">理智值 (SAN)</div>
            <div class="value-container">
              <el-input-number
                v-model="character.san"
                :min="0"
                :max="99"
                size="small"
                controls-position="right"
              />
              <span class="max-value">/ 99</span>
            </div>
            <el-progress 
              :percentage="(character.san / 99) * 100" 
              color="#e6a23c"
              :show-text="false"
            />
          </div>
        </div>
      </el-card>

      <!-- 技能系统 -->
      <el-card class="skills-card" shadow="never">
        <template #header>
          <div class="card-header">
            <el-icon><List /></el-icon>
            <span>技能</span>
            <el-button size="small" @click="addSkill">添加技能</el-button>
          </div>
        </template>
        
        <div class="skills-container">
          <div 
            v-for="(skill, skillName) in character.skills" 
            :key="skillName"
            class="skill-item"
          >
            <div class="skill-name">{{ skillName }}</div>
            <div class="skill-value">
              <el-input-number
                v-model="character.skills[skillName]"
                :min="0"
                :max="100"
                size="small"
                controls-position="right"
              />
            </div>
            <div class="skill-actions">
              <el-button size="small" type="danger" @click="removeSkill(skillName)">删除</el-button>
            </div>
          </div>
        </div>
      </el-card>

      <!-- 背包系统 -->
      <el-card class="inventory-card" shadow="never">
        <template #header>
          <div class="card-header">
            <el-icon><Box /></el-icon>
            <span>背包</span>
            <el-button size="small" @click="addItem">添加物品</el-button>
          </div>
        </template>
        
        <div class="inventory-grid">
          <div 
            v-for="(item, index) in character.inventory" 
            :key="index"
            class="inventory-item"
            draggable="true"
            @dragstart="handleDragStart($event, index)"
            @dragover="handleDragOver"
            @drop="handleDrop($event, index)"
          >
            <div class="item-name">{{ item.name }}</div>
            <div class="item-description">{{ item.description }}</div>
            <div class="item-actions">
              <el-button size="small" type="danger" @click="removeItem(index)">删除</el-button>
            </div>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 添加技能对话框 -->
    <el-dialog v-model="showAddSkillDialog" title="添加技能" width="400px">
      <el-form :model="newSkill" label-width="80px">
        <el-form-item label="技能名">
          <el-input v-model="newSkill.name" placeholder="请输入技能名" />
        </el-form-item>
        <el-form-item label="技能值">
          <el-input-number v-model="newSkill.value" :min="0" :max="100" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddSkillDialog = false">取消</el-button>
        <el-button type="primary" @click="confirmAddSkill">确定</el-button>
      </template>
    </el-dialog>

    <!-- 添加物品对话框 -->
    <el-dialog v-model="showAddItemDialog" title="添加物品" width="500px">
      <el-form :model="newItem" label-width="80px">
        <el-form-item label="物品名">
          <el-input v-model="newItem.name" placeholder="请输入物品名" />
        </el-form-item>
        <el-form-item label="描述">
          <el-input v-model="newItem.description" type="textarea" placeholder="请输入物品描述" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddItemDialog = false">取消</el-button>
        <el-button type="primary" @click="confirmAddItem">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, watch } from 'vue'
import { useGameStore } from '@/stores/game'
import { ElMessage } from 'element-plus'

const gameStore = useGameStore()

// 响应式数据
const character = ref({ ...gameStore.character })
const saving = ref(false)
const showAddSkillDialog = ref(false)
const showAddItemDialog = ref(false)
const newSkill = reactive({ name: '', value: 0 })
const newItem = reactive({ name: '', description: '' })
const draggedItemIndex = ref(null)

// 属性标签映射
const statLabels = {
  str: '力量',
  dex: '敏捷',
  pow: '意志',
  con: '体质',
  app: '外貌',
  siz: '体型',
  int: '智力',
  edu: '教育'
}

// 方法
const getStatLabel = (stat) => statLabels[stat] || stat

const getStatModifier = (value) => {
  if (value >= 80) return '+2'
  if (value >= 60) return '+1'
  if (value >= 40) return '+0'
  if (value >= 20) return '-1'
  return '-2'
}

const calculateHP = () => {
  const con = character.value.stats.con || 0
  const siz = character.value.stats.siz || 0
  return Math.floor((con + siz) / 2)
}

const calculateMP = () => {
  return character.value.stats.pow || 0
}

const getHPColor = () => {
  const percentage = (character.value.hp / calculateHP()) * 100
  if (percentage > 60) return '#67c23a'
  if (percentage > 30) return '#e6a23c'
  return '#f56c6c'
}

const addSkill = () => {
  newSkill.name = ''
  newSkill.value = 0
  showAddSkillDialog.value = true
}

const confirmAddSkill = () => {
  if (!newSkill.name.trim()) {
    ElMessage.warning('请输入技能名')
    return
  }
  
  character.value.skills[newSkill.name] = newSkill.value
  showAddSkillDialog.value = false
  ElMessage.success('技能添加成功')
}

const removeSkill = (skillName) => {
  delete character.value.skills[skillName]
  ElMessage.success('技能删除成功')
}

const addItem = () => {
  newItem.name = ''
  newItem.description = ''
  showAddItemDialog.value = true
}

const confirmAddItem = () => {
  if (!newItem.name.trim()) {
    ElMessage.warning('请输入物品名')
    return
  }
  
  character.value.inventory.push({
    name: newItem.name,
    description: newItem.description
  })
  showAddItemDialog.value = false
  ElMessage.success('物品添加成功')
}

const removeItem = (index) => {
  character.value.inventory.splice(index, 1)
  ElMessage.success('物品删除成功')
}

const handleDragStart = (event, index) => {
  draggedItemIndex.value = index
  event.dataTransfer.effectAllowed = 'move'
}

const handleDragOver = (event) => {
  event.preventDefault()
  event.dataTransfer.dropEffect = 'move'
}

const handleDrop = (event, dropIndex) => {
  event.preventDefault()
  
  if (draggedItemIndex.value === null || draggedItemIndex.value === dropIndex) {
    return
  }
  
  const draggedItem = character.value.inventory[draggedItemIndex.value]
  character.value.inventory.splice(draggedItemIndex.value, 1)
  character.value.inventory.splice(dropIndex, 0, draggedItem)
  
  draggedItemIndex.value = null
}

const saveCharacter = async () => {
  saving.value = true
  
  try {
    // 更新游戏状态中的角色数据
    gameStore.updateCharacter(character.value)
    
    // 这里可以添加保存到后端的逻辑
    await new Promise(resolve => setTimeout(resolve, 1000)) // 模拟API调用
    
    ElMessage.success('角色卡保存成功')
  } catch (error) {
    ElMessage.error('保存失败')
  } finally {
    saving.value = false
  }
}

const exportCharacter = () => {
  const dataStr = JSON.stringify(character.value, null, 2)
  const dataBlob = new Blob([dataStr], { type: 'application/json' })
  const url = URL.createObjectURL(dataBlob)
  
  const link = document.createElement('a')
  link.href = url
  link.download = `${character.value.name || 'character'}.json`
  link.click()
  
  URL.revokeObjectURL(url)
  ElMessage.success('角色卡导出成功')
}

const importCharacter = () => {
  const input = document.createElement('input')
  input.type = 'file'
  input.accept = '.json'
  
  input.onchange = (event) => {
    const file = event.target.files[0]
    if (!file) return
    
    const reader = new FileReader()
    reader.onload = (e) => {
      try {
        const importedCharacter = JSON.parse(e.target.result)
        character.value = { ...importedCharacter }
        gameStore.updateCharacter(character.value)
        ElMessage.success('角色卡导入成功')
      } catch (error) {
        ElMessage.error('文件格式错误')
      }
    }
    reader.readAsText(file)
  }
  
  input.click()
}

// 监听角色数据变化，自动更新生命值和魔法值
watch(() => character.value.stats, () => {
  character.value.hp = calculateHP()
  character.value.mp = calculateMP()
}, { deep: true })
</script>

<style scoped>
.character-sheet {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  height: 100%;
  overflow-y: auto;
}

.sheet-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.sheet-header h3 {
  margin: 0;
  display: flex;
  align-items: center;
  gap: 8px;
  color: #333;
}

.header-actions {
  display: flex;
  gap: 8px;
}

.sheet-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.info-card,
.stats-card,
.hp-mp-card,
.skills-card,
.inventory-card {
  border: 1px solid #eee;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: bold;
  color: #333;
}

.card-header .el-icon {
  color: #667eea;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 15px;
}

.stat-item {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 10px;
  background: #f8f9fa;
  border-radius: 6px;
}

.stat-label {
  font-weight: bold;
  min-width: 60px;
  color: #333;
}

.stat-value {
  flex: 1;
}

.stat-modifier {
  font-weight: bold;
  color: #667eea;
  min-width: 30px;
  text-align: center;
}

.hp-mp-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
}

.hp-item,
.mp-item,
.san-item {
  padding: 15px;
  background: #f8f9fa;
  border-radius: 6px;
}

.label {
  font-weight: bold;
  margin-bottom: 10px;
  color: #333;
}

.value-container {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 10px;
}

.max-value {
  color: #666;
  font-size: 14px;
}

.skills-container {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.skill-item {
  display: flex;
  align-items: center;
  gap: 15px;
  padding: 10px;
  background: #f8f9fa;
  border-radius: 6px;
}

.skill-name {
  font-weight: bold;
  min-width: 100px;
  color: #333;
}

.skill-value {
  flex: 1;
}

.skill-actions {
  min-width: 80px;
}

.inventory-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 15px;
}

.inventory-item {
  padding: 15px;
  background: #f8f9fa;
  border-radius: 6px;
  border: 2px dashed #ddd;
  cursor: move;
  transition: all 0.3s ease;
}

.inventory-item:hover {
  border-color: #667eea;
  background: #f0f9ff;
}

.item-name {
  font-weight: bold;
  margin-bottom: 5px;
  color: #333;
}

.item-description {
  font-size: 12px;
  color: #666;
  margin-bottom: 10px;
}

.item-actions {
  text-align: right;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .character-sheet {
    padding: 15px;
  }
  
  .stats-grid {
    grid-template-columns: 1fr;
  }
  
  .hp-mp-grid {
    grid-template-columns: 1fr;
  }
  
  .inventory-grid {
    grid-template-columns: 1fr;
  }
  
  .skill-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .skill-name {
    min-width: auto;
  }
  
  .skill-actions {
    min-width: auto;
    align-self: flex-end;
  }
}
</style>
